<template>
  <Page title="查看详情">
    <template #navBarCustom>
      <div class="flex items-center navBox">
        <div class="back" @click="back">
          <img class="icon" src="static/icons/back.png" mode="" />
          <span style="color: #fff">查看详情</span>
        </div>
        <div class="nav-bar-btns flex" style="margin-left: auto">
          <div class="item flex items-center">
            <span class="name text-white" @click="goToNextQuestion">下一题</span>
          </div>
        </div>
      </div>
    </template>
    <template #content>
      <div class="w-full h-full">
        <div class="container w-full h-full overflow-hidden bg-white flex flex-col">
          <div class="w-full h-full overflow-scroll">
            <div class="flex justify-center items-center pt-40px box-border">
              <HalfRound
                :size="340"
                :ratio="ratio"
                :lineWidth="24"
                :val="getProcess(score, totalScore)"
              >
                <template #hbhCustom>
                  <div
                    style="width: 3rem; height: 1.7rem; font-size: 0.3rem; line-height: 0.3rem"
                    class="customBox"
                  >
                    <div class="text-333 font-normal flex justify-center items-center">
                      <span>总得分：</span>
                    </div>
                    <div class="text-333 font-normal flex justify-center items-end">
                      <span
                        class="font-semibold"
                        :class="`text-${getScoreClass(score / totalScore)}`"
                        style="font-size: 0.5rem; line-height: 0.5rem"
                        >{{ score }}</span
                      >
                      <span :class="`text-${getScoreClass(score / totalScore)}`">分</span>
                      <span>/{{ totalScore }}分</span>
                    </div>
                    <div
                      class="flex justify-center items-center mt-6px"
                      style="font-size: 0.24rem; line-height: 0.24rem"
                    >
                      <span class="mr-6px text-A3A3A3">{{ difficulty.text }}</span>
                      <el-rate :value="difficulty.average" disabled></el-rate>
                    </div>
                  </div>
                </template>
              </HalfRound>
            </div>

            <!-- 各模块得分情况 -->
            <div class="modules">
              <div
                class="item text-333 font-normal flex justify-between mt-30px"
                @click="$router.push('/pages/exercise/record/detail/english/choose/index')"
                v-show="chooseTotalScore > 0"
              >
                <div class="title">
                  <span>听后选择</span>
                </div>
                <div class="detail">
                  <span :class="`text-${getScoreClass(chooseScore / chooseTotalScore)}`"
                    >{{ chooseScore }}分</span
                  >
                  <span>/{{ chooseTotalScore }}分</span>
                  <img class="icon ml-6px" src="static/icons/arrow-right.png" alt="" srcset="" />
                </div>
              </div>
              <div
                class="item text-333 font-normal flex justify-between mt-30px"
                @click="$router.push('/pages/exercise/record/detail/english/dialogue/index')"
                v-show="dialogueTotalScore > 0"
              >
                <div class="title">
                  <span>听后回答</span>
                </div>
                <div class="detail">
                  <span :class="`text-${getScoreClass(dialogueScore / dialogueTotalScore)}`"
                    >{{ dialogueScore }}分</span
                  >
                  <span>/{{ dialogueTotalScore }}分</span>
                  <img class="icon ml-6px" src="static/icons/arrow-right.png" alt="" srcset="" />
                </div>
              </div>
              <div
                class="item text-333 font-normal flex justify-between mt-30px"
                @click="$router.push('/pages/exercise/record/detail/english/read/index')"
                v-show="readTotalScore > 0"
              >
                <div class="title">
                  <span>短文朗读</span>
                </div>
                <div class="detail">
                  <span :class="`text-${getScoreClass(readScore / readTotalScore)}`"
                    >{{ readScore }}分</span
                  >
                  <span>/{{ readTotalScore }}分</span>
                  <img class="icon ml-6px" src="static/icons/arrow-right.png" alt="" srcset="" />
                </div>
              </div>
              <div
                class="item text-333 font-normal flex justify-between mt-30px"
                @click="$router.push('/pages/exercise/record/detail/english/fill/index')"
                v-show="fillTotalScore > 0"
              >
                <div class="title">
                  <span>听后记录</span>
                </div>
                <div class="detail">
                  <span :class="`text-${getScoreClass(fillScore / fillTotalScore)}`"
                    >{{ fillScore }}分</span
                  >
                  <span>/{{ fillTotalScore }}分</span>
                  <img class="icon ml-6px" src="static/icons/arrow-right.png" alt="" srcset="" />
                </div>
              </div>
              <div
                class="item text-333 font-normal flex justify-between mt-30px"
                @click="$router.push('/pages/exercise/record/detail/english/picture/index')"
                v-show="pictureTotalScore > 0"
              >
                <div class="title">
                  <span>听后转述</span>
                </div>
                <div class="detail">
                  <span :class="`text-${getScoreClass(pictureScore / pictureTotalScore)}`"
                    >{{ pictureScore }}分</span
                  >
                  <span>/{{ pictureTotalScore }}分</span>
                  <img class="icon ml-6px" src="static/icons/arrow-right.png" alt="" srcset="" />
                </div>
              </div>
              <!-- <div class="item text-333 font-normal flex justify-between mt-30px">
                <div class="title">
                  <span>听后记录并转述</span>
                </div>
                <div class="detail">
                  <span class="text-FF4040">3.5分</span>
                  <span>/12分</span>
                  <img class="icon ml-6px" src="static/icons/arrow-right.png" alt="" srcset="" />
                </div>
              </div> -->
            </div>
          </div>
        </div>
      </div>
    </template>
  </Page>
</template>

<script>
import Page from '@/components/page/newPage'
import { mapState } from 'vuex'
import { getKpointPracticeRecordQuestionList } from '@/api/exercise/record'
import { getEnglishPracticeApi, getNextEnglishQuestionApi } from '@/api/exercise'
import HalfRound from '../halfRound/index.vue'

export default {
  components: {
    Page,
    HalfRound
  },
  data() {
    return {
      ratio: 1,
      recordIds: '',
      subjectId: '',
      questions: [],
      difficulty: {
        average: 1,
        text: ''
      }
    }
  },
  computed: {
    ...mapState(['exerciseCenter']),
    // 听后选择
    chooseQuestions() {
      return this.questions
        .map((q) => {
          const {
            questionDto: {
              stem: { structure_type }
            }
          } = q

          if (structure_type === 'collector.choose') {
            return q
          } else {
            return null
          }
        })
        .filter((q) => !!q)
    },
    chooseScore() {
      let score = 0
      this.chooseQuestions.forEach((q) => {
        const { studentScore } = q

        score += studentScore
      })

      return score
    },
    chooseTotalScore() {
      let totalScore = 0
      this.chooseQuestions.forEach((q) => {
        const { questionScore } = q

        totalScore += questionScore
      })

      return totalScore
    },
    // 听后回答
    dialogueQuestions() {
      return this.questions
        .map((q) => {
          const {
            questionDto: {
              stem: { structure_type }
            }
          } = q

          if (structure_type === 'collector.dialogue') {
            return q
          } else {
            return null
          }
        })
        .filter((q) => !!q)
    },
    dialogueScore() {
      let score = 0
      this.dialogueQuestions.forEach((q) => {
        const { studentScore } = q

        score += studentScore
      })

      return score
    },
    dialogueTotalScore() {
      let totalScore = 0
      this.dialogueQuestions.forEach((q) => {
        const { questionScore } = q

        totalScore += questionScore
      })

      return totalScore
    },
    // 短文朗读
    readQuestions() {
      return this.questions
        .map((q) => {
          const {
            questionDto: {
              stem: { structure_type }
            }
          } = q

          if (structure_type === 'collector.read') {
            return q
          } else {
            return null
          }
        })
        .filter((q) => !!q)
    },
    readScore() {
      let score = 0
      this.readQuestions.forEach((q) => {
        const { studentScore } = q

        score += studentScore
      })

      return score
    },
    readTotalScore() {
      let totalScore = 0
      this.readQuestions.forEach((q) => {
        const { questionScore } = q

        totalScore += questionScore
      })

      return totalScore
    },
    // 听后记录
    fillQuestions() {
      return this.questions
        .map((q) => {
          const {
            questionDto: {
              stem: { structure_type }
            }
          } = q

          if (structure_type === 'collector.fill') {
            return q
          } else {
            return null
          }
        })
        .filter((q) => !!q)
    },
    fillScore() {
      let score = 0
      this.fillQuestions.forEach((q) => {
        const { studentScore } = q

        score += studentScore
      })

      return score
    },
    fillTotalScore() {
      let totalScore = 0
      this.fillQuestions.forEach((q) => {
        const { questionScore } = q

        totalScore += questionScore
      })

      return totalScore
    },
    // 听后转述
    pictureQuestions() {
      return this.questions
        .map((q) => {
          const {
            questionDto: {
              stem: { structure_type }
            }
          } = q

          if (structure_type === 'collector.picture') {
            return q
          } else {
            return null
          }
        })
        .filter((q) => !!q)
    },
    pictureScore() {
      let score = 0
      this.pictureQuestions.forEach((q) => {
        const { studentScore } = q

        score += studentScore
      })

      return score
    },
    pictureTotalScore() {
      let totalScore = 0
      this.pictureQuestions.forEach((q) => {
        const { questionScore } = q

        totalScore += questionScore
      })

      return totalScore
    },
    // 所有题型分数统计
    score() {
      const score =
        this.chooseScore + this.dialogueScore + this.readScore + this.fillScore + this.pictureScore

      try {
        return parseFloat(score).toFixed(1)
      } catch (error) {
        return 0
      }
    },
    totalScore() {
      const totalScore =
        this.chooseTotalScore +
        this.dialogueTotalScore +
        this.readTotalScore +
        this.fillTotalScore +
        this.pictureTotalScore

      return totalScore
    }
  },
  created() {
    const {
      query: { id = '', subjectId = '' }
    } = this.$route

    this.recordIds = id.split(',')
    this.subjectId = subjectId

    this.init()
  },
  mounted() {
    window.addEventListener('resize', (event) => {
      this.ratio = document.body.clientWidth / 1280
      // 在这里可以添加你想要执行的代码，比如更新页面布局或者调整媒体查询
    })
    this.ratio = document.body.clientWidth / 1280
  },
  methods: {
    back() {
      if (this.onBack) {
        this.onBack()
      } else {
        this.$router.go(-1)
      }
    },
    async init() {
      // 加载动画
      const loading = this.$loading({
        lock: true,
        text: '加载中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.5)'
      })
      // 一分钟内加载不成功关闭loading弹窗
      const timer = setTimeout(() => {
        loading.close()
      }, 60000)

      let totalDifficulty = 0
      let list
      if (Array.isArray(this.recordIds) && this.recordIds.length > 1) {
        const recordList = await Promise.all(
          this.recordIds.map(async (recordId) => {
            const {
              data: { list: recordItem }
            } = await getKpointPracticeRecordQuestionList({
              id: recordId
            })

            return recordItem[0]
          })
        )
        list = recordList
      } else if (Array.isArray(this.recordIds) && this.recordIds.length === 1) {
        const {
          data: { list: recordList }
        } = await getKpointPracticeRecordQuestionList({
          id: this.recordIds[0]
        })
        list = recordList
      } else {
        // 未传入recordId
        list = []
      }

      // 关闭加载动画
      clearTimeout(timer)
      loading.close()

      if (Array.isArray(list) && list.length > 0) {
        this.questions = list.map((i) => {
          const {
            questionDto: { difficulty, stem, answer },
            studentAnswer
          } = i

          const deepCopy = (data) => JSON.parse(JSON.stringify(data))

          totalDifficulty += difficulty

          const copyQuestionDto = deepCopy(i.questionDto)
          copyQuestionDto.stem = JSON.parse(stem)
          const { structure_type } = copyQuestionDto.stem
          copyQuestionDto.answer = JSON.parse(answer)
          copyQuestionDto.questionIds = [i.questionId]

          switch (structure_type) {
            case 'collector.choose':
              copyQuestionDto.stem.info.question = [i.questionDto]
              copyQuestionDto.remoteStudentAnswer = [
                {
                  studentScore: i.studentScore,
                  questionScore: i.questionScore,
                  studentAnswer: JSON.parse(studentAnswer)
                }
              ]
              break
            case 'collector.dialogue':
              copyQuestionDto.remoteStudentAnswer = {
                studentScore: i.studentScore,
                questionScore: i.questionScore,
                studentAnswer: JSON.parse(studentAnswer)
              }
              break
            case 'collector.read':
              copyQuestionDto.remoteStudentAnswer = {
                studentScore: i.studentScore,
                questionScore: i.questionScore,
                studentAnswer: JSON.parse(studentAnswer)
              }
              break
            case 'collector.fill':
              copyQuestionDto.remoteStudentAnswer = {
                studentScore: i.studentScore,
                questionScore: i.questionScore,
                studentAnswer: JSON.parse(studentAnswer)
              }
              break
            case 'collector.picture':
              copyQuestionDto.remoteStudentAnswer = {
                studentScore: i.studentScore,
                questionScore: i.questionScore,
                studentAnswer: JSON.parse(studentAnswer)
              }
              break
            default:
              break
          }

          i.questionDto = copyQuestionDto

          return i
        })

        const {
          questionDto: { courseId, difficultyLevel, typeId }
        } = list[0]
        this.$store.commit('setCurrentPractice', {
          record: {
            id: this.recordIds[0],
            courseId: this.subjectId,
            difficultyLevel,
            questionTypeId: typeId
          },
          questions: this.questions,
          questionIndex: 0
        })
      }

      try {
        const average = totalDifficulty / this.questions.length
        if (average <= 0.3) {
          this.difficulty.average = 5
          this.difficulty.text = '困难'
        } else if (average > 0.3 && average <= 0.5) {
          this.difficulty.average = 4
          this.difficulty.text = '较难'
        } else if (average > 0.5 && average <= 0.8) {
          this.difficulty.average = 3
          this.difficulty.text = '适中'
        } else if (average > 0.8 && average <= 0.9) {
          this.difficulty.average = 2
          this.difficulty.text = '较易'
        } else {
          this.difficulty.average = 1
          this.difficulty.text = '容易'
        }
      } catch (error) {}
    },
    getScoreClass(proportion) {
      if (typeof proportion != 'number') return

      if (proportion >= 0 && proportion < 0.4) {
        return 'FF4040'
      } else if (proportion >= 0.4 && proportion < 0.8) {
        return 'F8AC23'
      } else {
        return '30C9A1'
      }
    },
    getProcess(val1, val2) {
      if (val2 - 0 <= 0) {
        return 0
      }
      return (val1 - 0) / (val2 - 0)
    },
    async goToNextQuestion() {
      const {
        record: { courseId, difficultyLevel, questionTypeId }
      } = this.exerciseCenter.currentPractice
      const questionId =
        Array.isArray(this.questions) && this.questions.length > 0
          ? this.questions[0].questionId
          : undefined

      // 加载动画
      const loading = this.$loading({
        lock: true,
        text: '加载中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.5)'
      })
      // 一分钟内加载不成功关闭loading弹窗
      const timer = setTimeout(() => {
        loading.close()
      }, 60000)

      const { data: record } = await getEnglishPracticeApi({
        courseId,
        difficultyLevel,
        questionTypeId
      })
      const { data: question, msg } = await getNextEnglishQuestionApi({
        questionId,
        courseId,
        difficultyLevel,
        questionTypeId,
        kpointPracticeId: record.id
      })

      // 关闭加载动画
      clearTimeout(timer)
      loading.close()

      if (!question) {
        this.$message.error(msg)
      } else {
        this.$store.commit('setCurrentPractice', {
          record: Object.assign(record, { kpointIds: [record.kpointId] }),
          questions: [question],
          questionIndex: 0
        })

        this.$router.push('/pages/exercise/practice/english/index').then(() => {
          this.$store.commit('setCurrentPractice', {
            record: Object.assign(record, { kpointIds: [record.kpointId] }),
            questions: [question],
            questionIndex: 0
          })
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.customBox {
  display: flex;
  flex-direction: column;
  justify-content: flex-end;
}
.navBox {
  padding: 0 20px;
  box-sizing: border-box;
}
.back {
  height: 100%;
  display: flex;
  align-items: center;
  font-size: 28px;

  .icon {
    width: 17.14px;
    height: 30px;
    margin-right: 11px;
  }
}
.nav-bar-btns {
  .item {
    height: 30px;
    .icon {
      width: 22px;
      height: 22px;
    }

    .name {
      font-size: 22px;
      line-height: 22px;
    }
  }
}

.container {
  .overview {
    font-size: 20px;
  }

  .modules {
    font-size: 26px;
    padding: 0 390px;

    .item {
      .title {
      }

      .detail {
        .icon {
          width: 9.14px;
          height: 16px;
        }
      }
    }
  }
}

/deep/ .el-rate {
  height: auto;
}
</style>
